How to implement interface in java? Please provide a sample.
How to implement interface in java? Please provide a sample.
393
05-Sep-2023
Aryan Kumar
06-Sep-2023A java interface is a blueprint for a class. Defines the methods that the class must implement. Interfaces cannot be instantiated, but can be implemented by classes.
Implementing an interface in Java, requires using the
implementskeyword. For example, the following code shows how the Runnable interface implemented:Java
The
Runnableinterface defines a single method calledrun(). TheMyThreadclass implements therun()method by providing its own implementation.Here's another example of how to implementing an interface in Java:
Java
The
Shapeinterface defines a single method calleddraw(). TheCircleclass implements thedraw()method by providing its own implementation.If a class implements an interface, it must provide implementations for all the methods defined in that interface. A class is said to be an abstract class if it foes not provide implementations for all the methods defined in the interface, then the class is said to be
abstract.